package com.axend.sofa.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_base.bean.BleDeviceEntity
import com.axend.lib_base.utils.log.MyLogUtils

/**
 * @author axend
 * @date 2022/3/29
 * @desc connect ble viewModel
 */
class BleConnectViewModel : BaseViewModel() {

    /*蓝牙是否打开*/
    private var _blueToothIsEnable: MutableLiveData<Boolean> = MutableLiveData()
    val blueToothEnable: LiveData<Boolean> get() = _blueToothIsEnable


    /*是否在扫描*/
    private var _isScanning: MutableLiveData<Boolean> = MutableLiveData()
    val isScanning: LiveData<Boolean> get() = _isScanning

    /*设备数据*/
    private var _devList: MutableLiveData<List<BleDeviceEntity>> = MutableLiveData()
    val devList: LiveData<List<BleDeviceEntity>> get() = _devList

    /*记录选择的索引*/
    private var _selectIndex: MutableLiveData<Int> = MutableLiveData()
    val selectIndex: LiveData<Int> get() = _selectIndex


    /**
     * 蓝牙是否已经打开
     */
    fun setBlueToothEnable(enable: Boolean) {
        launchOnUI { _blueToothIsEnable.postValue(enable) }
    }


    /**
     * 扫描状态，是否在扫描
     */
    fun setIsScan(isScan: Boolean) {
        launchOnUI { _isScanning.postValue(isScan) }
    }


    /**
     * 添加数据（单个添加）
     */
    fun addDevice(device: BleDeviceEntity) {
        var dataList = _devList.value.orEmpty().toMutableList()
        /*判断列表中是否有相同设备*/
        if (dataList.any { it.bleDevice.bleAddress == device.bleDevice.bleAddress }) {
            return
        }
        if (device.bleDevice.bleName.isNullOrEmpty()) {
            return
        }
        if (device.bleDevice.bleName.contains("ASX")) {
            dataList.add(device)
            _devList.postValue(dataList)
        }
    }

    /**
     * 清除数据
     */
    fun clearDevList() {
        _devList.postValue(emptyList())
    }


    /**
     * 设置索引
     */
    fun setSelectIndex(index: Int) {
        launchOnUI { _selectIndex.postValue(index) }
    }
}